package dom.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
	public static void addCookie(String cookieName,int time,
			HttpServletRequest request,HttpServletResponse response,
			String stuCode,String password)
	{
		//查询cookie库中是否有该用户
		Cookie cookie=getCookieByName(request,cookieName);
		if(cookie!=null){
			cookie.setValue(stuCode+"#"+password);
		}else{
			cookie=new Cookie(cookieName, stuCode+"#"+password);
		}
		//时间
		cookie.setMaxAge(time);
		//作用范围
		cookie.setPath("request.getContextPath()");
		//保存cookie信息
		response.addCookie(cookie);
		
	}
	public static Cookie getCookieByName(HttpServletRequest request,String cookieName){
		//获取所有Cookie
				Cookie[] cookies=request.getCookies();
				if(cookies !=null && cookies.length>0){
					for(Cookie cookie : cookies){
						if(cookie.getName().equals(cookieName)){
							return cookie;
						}
					}
				}
				return null;
	}
}
